package study.jy.utils;


import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import study.jy.common.Constants;
import study.jy.common.enums.RoleEnum;
import study.jy.entity.Account;
import study.jy.service.AdminService;

import java.util.Date;

/**
 * token工具类
 */
@Component
public class JWTUtil {

    private static final Logger log = LoggerFactory.getLogger(JWT.class);

    @Resource
    private AdminService adminService;

    private static AdminService staticAdminService;

    @PostConstruct
    public void init() {
        staticAdminService = adminService;
    }

    /**
     * 生成token
     * @param data
     * @param sign
     * @return
     */
    public static String createToken(String data, String sign) {
        // audience：是存储数据的一个媒介,存储用户ID和用户的角色
        return JWT.create().withAudience(data)
                .withExpiresAt(DateUtil.offsetDay(new Date(), 1)) // 过期时间为一天后
                .sign(Algorithm.HMAC256(sign)); // 签名算法
    }

    /**
     * 获取当前登录的用户
     */
    public static Account getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader(Constants.TOKEN);
            String audience = JWT.decode(token).getAudience().get(0);
            String[] userRole = audience.split("-");
            Integer userId = Integer.valueOf(userRole[0]);
            String role = userRole[1];
            if (RoleEnum.ADMIN.name().equals(role)) {
                return staticAdminService.selectById(userId);
            }
        } catch (Exception e) {
            log.error("获取当前登录用户出错", e);
        }
        return null;
    }
}
